using System.Drawing;

namespace PlantsVsZombies
{
    public class Game
    {
        private readonly List<Plant> plants = new();
        private readonly List<Zombie> zombies = new();
        private readonly List<Projectile> projectiles = new();
        private readonly List<Sun> suns = new();
        private int sunCount = 50;
        private int score = 0;
        private int wave = 1;
        private readonly Random random = new();
        private int selectedPlantIndex = 0;

        public event EventHandler? GameOver;
        public event EventHandler<string>? AchievementUnlocked;

        public void Update()
        {
            // 更新所有游戏对象
            UpdatePlants();
            UpdateZombies();
            UpdateProjectiles();
            UpdateSuns();

            // 生成阳光
            if (random.Next(100) < 2)
            {
                GenerateSun();
            }

            // 生成僵尸
            if (random.Next(100) < wave)
            {
                GenerateZombie();
            }

            // 检查游戏是否结束
            CheckGameOver();
        }

        public void Draw(Graphics g)
        {
            // 绘制所有游戏对象
            foreach (var plant in plants)
            {
                plant.Draw(g);
            }

            foreach (var zombie in zombies)
            {
                zombie.Draw(g);
            }

            foreach (var projectile in projectiles)
            {
                projectile.Draw(g);
            }

            foreach (var sun in suns)
            {
                sun.Draw(g);
            }

            // 绘制UI
            DrawUI(g);
        }

        public void HandleMouseClick(Point location)
        {
            // 处理点击事件
            foreach (var sun in suns.ToList())
            {
                if (sun.Contains(location))
                {
                    suns.Remove(sun);
                    sunCount += 25;
                    ResourceManager.PlaySound("sun");
                    return;
                }
            }

            // 处理植物放置
            // TODO: 实现植物放置逻辑
        }

        private void UpdatePlants()
        {
            foreach (var plant in plants)
            {
                plant.Update();
                if (plant.CanShoot())
                {
                    projectiles.Add(plant.Shoot());
                    ResourceManager.PlaySound("plant");
                }
            }
        }

        private void UpdateZombies()
        {
            foreach (var zombie in zombies.ToList())
            {
                zombie.Update();
                if (zombie.HasReachedHouse())
                {
                    GameOver?.Invoke(this, EventArgs.Empty);
                }
            }
        }

        private void UpdateProjectiles()
        {
            foreach (var projectile in projectiles.ToList())
            {
                projectile.Update();
                if (projectile.IsOutOfBounds())
                {
                    projectiles.Remove(projectile);
                    continue;
                }

                foreach (var zombie in zombies.ToList())
                {
                    if (projectile.CollidesWith(zombie))
                    {
                        zombie.TakeDamage(projectile.Damage);
                        projectiles.Remove(projectile);
                        if (zombie.IsDead)
                        {
                            zombies.Remove(zombie);
                            score += 100;
                            CheckAchievements();
                        }
                        break;
                    }
                }
            }
        }

        private void UpdateSuns()
        {
            foreach (var sun in suns.ToList())
            {
                sun.Update();
                if (sun.HasFallen())
                {
                    suns.Remove(sun);
                }
            }
        }

        private void GenerateSun()
        {
            var x = random.Next(100, 700);
            suns.Add(new Sun(new Point(x, 0)));
        }

        private void GenerateZombie()
        {
            var types = new[] { "basic_zombie", "cone_zombie", "bucket_zombie" };
            var type = types[random.Next(types.Length)];
            var y = random.Next(100, 500);
            Zombie zombie;
            switch (type)
            {
                case "basic_zombie":
                    zombie = new BasicZombie(new Point(800, y));
                    break;
                case "cone_zombie":
                    zombie = new ConeZombie(new Point(800, y));
                    break;
                case "bucket_zombie":
                    zombie = new BucketZombie(new Point(800, y));
                    break;
                default:
                    zombie = new BasicZombie(new Point(800, y));
                    break;
            }
            zombies.Add(zombie);
        }

        private void CheckGameOver()
        {
            if (zombies.Any(z => z.HasReachedHouse()))
            {
                GameOver?.Invoke(this, EventArgs.Empty);
            }
        }

        private void CheckAchievements()
        {
            if (score >= 1000)
            {
                AchievementUnlocked?.Invoke(this, "初级植物学家");
            }
            if (score >= 5000)
            {
                AchievementUnlocked?.Invoke(this, "中级植物学家");
            }
            if (score >= 10000)
            {
                AchievementUnlocked?.Invoke(this, "高级植物学家");
            }
        }

        private void DrawUI(Graphics g)
        {
            // 绘制阳光数量
            g.DrawString($"阳光: {sunCount}", new Font("Arial", 16), Brushes.Yellow, new Point(10, 10));
            
            // 绘制分数
            g.DrawString($"分数: {score}", new Font("Arial", 16), Brushes.White, new Point(10, 40));
            
            // 绘制波数
            g.DrawString($"波数: {wave}", new Font("Arial", 16), Brushes.White, new Point(10, 70));
        }

        public void SelectPlant(int plantIndex)
        {
            selectedPlantIndex = plantIndex;
        }

        public void PlacePlant(int row, int col)
        {
            // 简单实现：每个格子80x80，左上角(100,50)
            var pos = new Point(col * 80 + 100, row * 80 + 50);
            Plant? plant = selectedPlantIndex switch
            {
                0 => new Peashooter(pos),
                1 => new Sunflower(pos),
                2 => new WallNut(pos),
                3 => new SnowPea(pos),
                _ => null
            };
            if (plant != null && sunCount >= plant.Cost && !plants.Any(p => p.Position == pos))
            {
                plants.Add(plant);
                sunCount -= plant.Cost;
                ResourceManager.PlaySound("plant");
            }
        }
    }
} 